import { useEffect,useState } from "react";
import { Button  } from "@nextui-org/react";

function fetchDate() { 
  return new Promise((resolve, reject) => { 
    setTimeout(() => {
      let data = [{name:'jake',age:10,w:1,h:2},{name:'Tom',age:20,w:3,h:6},{name:'Tina',age:25,w:5,h:10}]
        resolve(data)
     }, 0.5*1000);
  })
}

//这个Effect是用来调用接口的

// export default function UseEffectModule() {
//   //调用函数的Effect
//   const [list,setList]= useState([])
//   useEffect( () => {
//     const getFetch = async () => {
//       let res = await fetchDate()
//       console.log(res,'11')
//       setList(res)
//       console.log(list,'********')
//     }
//     getFetch();
//   },[])


  
//   return (
//     <>
//       <ul>
//         {list.length && list.map((v, index) => (
//           <li key={index}>{v.name}/{v.age}/{v.w}/{v.h}</li>
//           )
//          )}
//       </ul>
//     </>
//   )
// }

// 这个是用来订阅事件的
function dispatchEvent() { 
  console.log('start event')
  const event= new Event('open-window')
  document.dispatchEvent(event)
}

function receiver() { 
    console.log('this is open-window')
}

function createEventListener() { 
  document.addEventListener('open-window',receiver )
}

function removeEventListener() { 
  console.log('close open-window');
  document.removeEventListener('open-window', receiver) 
}
export default function UseEffectModule() { 

  useEffect(() => { 
    createEventListener()
    return () => { 
      removeEventListener()
    }
    
  },[])

  return (
    <>
      <Button size="sm" color="secondary" onClick={() => { dispatchEvent() }}>触发事件</Button>
    </>
  )
}